<?php

namespace App\Http\Controllers\Laifei\Shopkeeper;

use App\Http\Controllers\ClientController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ShopkeeperStoreController extends ClientController
{

    public function index()
    {
        $all = $this->all;
        $pageSize = $all['pageSize'] ?? 20;
        $pageNo = $all['pageNo'] ?? 1;

        try {

            $where = function ($query) use ($all) {
                if (isset($all['we_id'])) {
                    $query->where('shop.we_id', '=', $all['we_id']);
                }
                if (isset($all['openid'])) {
                    $query->where('lu.openid', '=', $all['openid']);
                }
                if (isset($all['nickname'])) {
                    $query->where('lu.nickname', 'like', '%' . $all['nickname'] . '%');
                }
            };

            $total = DB::table('shop')
                ->leftJoin('lottery_users as lu', 'shop.we_id', '=', 'lu.we_id')
                ->where($where)
                ->distinct('shop.we_id')
                ->count();

            $info = DB::table('shop')
                ->leftJoin('lottery_users as lu', 'shop.we_id', '=', 'lu.we_id')
                ->where($where)
                ->select('shop.we_id', 'lu.openid', 'lu.nickname')
                ->selectRaw('COUNT(*) as shop_count')
                ->groupBy('shop.we_id')
                ->skip(($pageNo - 1) * $pageSize)
                ->take($pageSize)
                ->get();

            $we_ids = $info->pluck('we_id')->toArray();

            $info = $info->keyBy('we_id')->toArray();
            $info = json_decode(json_encode($info), true);

            // 探店余量
            $remaining = DB::table('explore_remaining')
                ->whereIn('we_id',$we_ids)
                ->get();
            // 查询霸王餐余量
            $lottery_remaining = DB::table('lottery_remaining')
                ->whereIn('we_id',$we_ids)
                ->get();
            foreach ($we_ids as $we_id) {
                $info[$we_id]['channel_remaining'] = $remaining->where('we_id','=',$we_id)->sum('remaining_times');
                $info[$we_id]['channel_in_use'] = $remaining->where('we_id','=',$we_id)->sum('in_use_times');
                $info[$we_id]['lottery_remaining'] = $lottery_remaining->where('we_id','=',$we_id)->sum('remaining_times');
                $info[$we_id]['lottery_in_use'] = $lottery_remaining->where('we_id','=',$we_id)->sum('in_use_times');
            }

            return $this->setReturnJson(0, 'success', ['total' => $total, 'info' => array_values($info)]);
        } catch (\Exception $e) {
            Log::error(ShopkeeperStoreController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '查询失败', ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
        }

    }

}
